package com.peng.service.impl;

import com.peng.apis.AccountFeignApi;
import com.peng.apis.StorageFeignApi;
import com.peng.entities.Order;
import com.peng.mapper.OrderMapper;
import com.peng.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
@GlobalTransactional(name = "peng-create-order", rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource //调用库存微服务
    private StorageFeignApi storageFeignApi;
    @Resource // 调用账户微服务
    private AccountFeignApi accountFeignApi;

    @Override
    public void create(Order order) {
        //xid全局事务id的检查，重要！！！
        String xid = RootContext.getXID();
        //1 新建订单
        log.info("------->开始新建订单，全局事务id为：{}", xid);
        //订单在创建时的状态是 0
        order.setStatus(0);
        int result = orderMapper.insertSelective(order);
        Order orderFromDB = null;
        if(result > 0){
            //插入成功 从mysql中查出刚插入的记录
            orderFromDB = orderMapper.selectOne(order);
            //2 扣减库存
            log.info("------->订单微服务开始调用库存，做扣减Count");
            storageFeignApi.decrease(orderFromDB.getProductId(), orderFromDB.getCount());
            //3 扣减账户
            log.info("------->订单微服务开始调用账户，做扣减Money");
            accountFeignApi.decrease(orderFromDB.getUserId(), orderFromDB.getMoney());
            //4 修改订单状态
            log.info("------->订单微服务开始修改订单状态");
            //订单在完成的状态是 1
            orderFromDB.setStatus(1);

            // 匹配相对应的数据 [where] 跟Lambda表达式的写法差不多
            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", orderFromDB.getUserId());
            criteria.andEqualTo("status", 0);

            int updateResult = orderMapper.updateByExampleSelective(orderFromDB, example);
            log.info("------->订单微服务修改订单状态结束，结果：{}", updateResult > 0);
        }
        System.out.println();
        log.info("------->结束新建订单，{}", xid);
    }
}
